# gui.py
import tkinter as tk
from tkinter import messagebox, simpledialog, filedialog
from config_manager import save_config, load_config
from alarm_core import AlarmClock
import os


class AlarmGUI:
    def __init__(self, root):
        self.root = root
        self.root.title("⏰ 桌面闹钟")
        self.root.geometry("580x520")
        self.root.resizable(False, False)

        # 加载配置
        loaded_alarms, loaded_sound = load_config()
        self.alarms = loaded_alarms
        self.alarm_sound_file = loaded_sound

        # 如果没有配置铃声，尝试使用默认文件
        if not self.alarm_sound_file and self._default_sound_exists():
            self.alarm_sound_file = "alarm.mp3"

        # 初始化闹钟线程
        self.alarm_clock = AlarmClock(self)

        # 构建界面
        self._build_ui()

        # 绑定关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

    def _default_sound_exists(self):
        return "alarm.mp3" if os.path.exists("alarm.mp3") else None

    def _build_ui(self):
        tk.Label(self.root, text="🔔 闹钟列表", font=("Microsoft YaHei", 16, "bold")).pack(pady=10)

        self.listbox = tk.Listbox(self.root, width=65, height=14, font=("Arial", 11))
        self.listbox.pack(pady=10)

        btn_frame = tk.Frame(self.root)
        btn_frame.pack(pady=10)

        tk.Button(btn_frame, text="➕ 添加固定时间", command=self.add_fixed_alarm, width=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="⏱️ 添加每小时分钟", command=self.add_hourly_alarm, width=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="🗑️ 删除选中闹钟", command=self.delete_alarm, width=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="🎵 设置铃声文件", command=self.set_alarm_sound, width=15).pack(side=tk.LEFT, padx=5)

        # 显示当前铃声
        current_sound = self.alarm_sound_file or "系统提示音"
        self.sound_label = tk.Label(self.root, text=f"🔊 当前铃声：{current_sound}", fg="gray", font=("Arial", 9))
        self.sound_label.pack(pady=5)

        # 刷新列表
        self.update_listbox()

    def update_listbox(self):
        self.listbox.delete(0, tk.END)
        for alarm in self.alarms:
            if alarm['type'] == 'fixed':
                self.listbox.insert(tk.END, f"🕒 固定时间: {alarm['time']}")
            else:
                self.listbox.insert(tk.END, f"⏱️ 每小时第 {alarm['minute']} 分钟")

    def add_fixed_alarm(self):
        time_str = simpledialog.askstring("添加闹钟", "请输入时间 (HH:MM 格式):")
        if time_str:
            try:
                datetime.datetime.strptime(time_str, "%H:%M")
                alarm = {'type': 'fixed', 'time': time_str, 'triggered_today': False}
                self.alarms.append(alarm)
                self.update_listbox()
                self.auto_save()
            except ValueError:
                messagebox.showerror("错误", "时间格式错误，请输入 HH:MM 格式")

    def add_hourly_alarm(self):
        minute_str = simpledialog.askstring("添加每小时闹钟", "请输入分钟数 (0-59):")
        if minute_str and minute_str.isdigit():
            minute = int(minute_str)
            if 0 <= minute <= 59:
                alarm = {'type': 'hourly', 'minute': minute}
                self.alarms.append(alarm)
                self.update_listbox()
                self.auto_save()
            else:
                messagebox.showerror("错误", "分钟数必须在 0-59 之间")
        else:
            messagebox.showerror("错误", "请输入有效数字")

    def delete_alarm(self):
        selected = self.listbox.curselection()
        if selected:
            idx = selected[0]
            del self.alarms[idx]
            self.update_listbox()
            self.auto_save()
        else:
            messagebox.showwarning("提示", "请先选中一个闹钟")

    def set_alarm_sound(self):
        file_path = filedialog.askopenfilename(
            title="选择闹钟铃声",
            filetypes=[("音频文件", "*.mp3 *.wav *.ogg"), ("所有文件", "*.*")]
        )
        if file_path:
            self.alarm_sound_file = file_path
            self.sound_label.config(text=f"🔊 当前铃声：{os.path.basename(file_path)}")
            self.auto_save()
            messagebox.showinfo("成功", f"铃声已设置为：{os.path.basename(file_path)}")

    def show_alarm_message(self, msg):
        """显示闹钟弹窗（可被 alarm_core 调用）"""
        messagebox.showinfo("闹钟提醒", msg)

    def auto_save(self):
        """自动保存配置"""
        save_config(self.alarms, self.alarm_sound_file)

    def on_closing(self):
        if messagebox.askokcancel("退出", "确定要退出闹钟程序吗？"):
            self.alarm_clock.stop()
            self.auto_save()  # 退出前保存
            self.root.destroy()